import {
  fetchUserCenter
} from '../../services/usercenter/fetchUsercenter';
import Toast from 'tdesign-miniprogram/toast/index';
import {
  wxLogin,
  getSwiper,
  getBizConfList
} from '../../api/index'

const menuData = [
  [{
      title: '在线客服',
      tit: '',
      url: '',
      type: 'ask',
      imgsrc: '/image/ask@2x.png'
    },
    {
      title: '联系电话',
      tit: '',
      url: '',
      type: 'phone',
      imgsrc: '/image/phone.png',
      phoneNum: '400-0000-0000'
    },
  ],
];

const orderTagInfos = [{
    title: '待支付',
    src: '/image/waitpay.png',
    orderNum: 0,
    tabType: 5,
    status: 1,
  },
  {
    title: '待使用',
    src: '/image/time.png',
    orderNum: 0,
    tabType: 10,
    status: 1,
  },
  {
    title: '已完成',
    src: '/image/finsh.png',
    orderNum: 0,
    tabType: 50,
    status: 1,
  },
  {
    title: '已退款',
    src: '/image/refond.png',
    orderNum: 0,
    tabType: 160,
    status: 1,
  },
];


Page({
  data: {
    image: 'https://tdesign.gtimg.com/mobile/demos/avatar1.png',
    userInfo: {},
    avatarUrl: '/image/mine-av.png',
    nickName: '时忆旅拍',
    accessToken: '',
    refreshToken: '',
    bgi: [],
    phone: '', //联系电话
    showAuthButton: false,
    visible: false,
  },
  onLoad() {
    this.getVersionInfo();
    this.init();
  },

  onShow() {
    this.getTabBar().init();
    this.init();
  },
  onPullDownRefresh() {
    this.init();
  },

  init() {
    this.fetUseriInfoHandle()
    this.getSwiperFn()
    this.getBizConfListFn()
    this.showDialogFn()
    this.fetchToken()
  },

  async fetchToken() {
    const token = await wx.getStorageSync('user_token')
    this.setData({
      accessToken: token
    })
  },

  // 弹出弹框
  showDialogFn() {
    const userInfo = wx.getStorageSync('user_userInfo')
    console.log(userInfo, 'userInfouserInfo')
    if (!userInfo) {
      this.setData({
        visible: true
      })
    }
  },
  confirmHandle() {
    console.log('111')
    wx.getUserInfo({
      success: (userInfoRes) => {
        // 用户信息获取成功  
        console.log(userInfoRes, 'userInfoRes22')
        this.setData({
          userInfo: userInfoRes.userInfo,
          avatarUrl: this.data.avatarUrl,
          nickName: userInfoRes.userInfo.nickName,
        });
        this.setStorage('user_userInfo', userInfoRes.userInfo);
        this.login();
      },
      fail: (err) => {
        // 获取用户信息失败  
        this.setData({
          visible: true // 显示授权按钮  
        });
      }
    });
    this.setData({
      visible: false
    })
  },
  cancelHandle() {
    this.setData({
      visible: false
    })
  },
  handleGetUserInfo: function () {
    // 检查是否已经授权  
    wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.userInfo']) {
          this.getUserProfile();
        } else {
          wx.authorize({
            scope: 'scope.userInfo',
            success: () => {
              wx.getUserProfile({
                desc: '用于微信登录',
                success: (userInfoRes) => {
                  // 用户信息获取成功  
                  console.log(userInfoRes, 'userInfoRes11')
                  this.setData({
                    userInfo: userInfoRes.userInfo,
                    avatarUrl: this.data.avatarUrl,
                    nickName: userInfoRes.userInfo.nickName,
                  });

                  // 获取到用户信息后，进行登录操作  
                  this.login();
                },
                fail: (err) => {
                  // 获取用户信息失败  
                  this.setData({
                    showAuthButton: true // 显示授权按钮  
                  });
                }
              });
              // this.getUserInfo();
            },
            fail: () => {
              // 用户拒绝授权，提示用户  
              wx.showToast({
                title: '您拒绝了授权，无法获取用户信息',
                icon: 'none'
              });
            }
          });
        }
      }
    });
  },

  getUserProfile: function () {
    // 获取用户信息  
    wx.getUserInfo({
      desc: '用于微信登录',
      success: (userInfoRes) => {
        // 用户信息获取成功  
        console.log(userInfoRes, 'userInfoRes22')
        this.setData({
          userInfo: userInfoRes.userInfo,
          avatarUrl: this.data.avatarUrl,
          nickName: userInfoRes.userInfo.nickName,
        });

        // 获取到用户信息后，进行登录操作  
        this.login();
      },
      fail: (err) => {
        // 获取用户信息失败  
        this.setData({
          showAuthButton: true // 显示授权按钮  
        });
      }
    });
  },

  // 封装存储函数  
  async setStorage(key, data) {
    try {
      const res = await wx.setStorage({
        key,
        data
      });
      console.log(`${key} 存储成功`, res);
    } catch (err) {
      console.error(`${key} 存储失败`, err);
    }
  },

  // 登录函数  
  async login() {
    try {
      const wxLoginRes = await new Promise((resolve, reject) => {
        wx.login({
          success: (res) => {
            console.log(res, '登录成功响应');
            resolve(res);
          },
          fail: (err) => {
            console.error('登录失败', err);
            // reject(err);
          }
        });
      });

      const loginData = await wxLogin({
        code: wxLoginRes.code,
        avatar: this.data.avatarUrl,
        nickName: this.data.nickName,
      });
      this.setData({
        accessToken: loginData.data.accessToken,
        refreshToken: loginData.data.refreshToken
      });


      await this.setStorage('user_token', loginData.data.accessToken);
      await this.setStorage('user_refreshToken', loginData.data.refreshToken);

      wx.showToast({
        title: '登录成功',
        icon: 'success',
        duration: 2000
      });
    } catch (error) {
      console.error('登录过程中发生错误', error);
      // 可以在这里添加全局错误处理逻辑，比如显示错误提示给用户  
    }
  },
  getSwiperFn() {
    getSwiper({
      id: 26
    }).then((res) => {
      console.log(res.data.item, 'res');
      const urls = res.data.item.map(v => "https://oss.peibanmao.com/" + v.url);
      this.setData({
        bgi: urls,
      });
    })
  },
  getBizConfListFn() {
    getBizConfList({
      code: 'SYLP_OFFLINE'
    }).then(res => {
      this.setData({
        phone: res.data.phoneNum || ''
      })
      console.log(this.data.phone, '555')
    })
  },
  fetUseriInfoHandle() {
    fetchUserCenter().then(
      ({
        userInfo,
        countsData,
        orderTagInfos: orderInfo,
        customerServiceInfo,
      }) => {
        const info = orderTagInfos.map((v, index) => ({
          ...v,
          ...orderInfo[index],
        }));
        this.setData({
          userInfo,
          menuData,
          orderTagInfos: info,
          customerServiceInfo,
          currAuthStep: 1,
        });
        wx.stopPullDownRefresh();
      },
    );
  },

  onClickCell({
    currentTarget
  }) {
    const {
      type
    } = currentTarget.dataset;
    switch (type) {
      case 'favor': {
        Toast({
          context: this,
          selector: '#t-toast',
          message: '你点击了收藏',
          icon: '',
          duration: 1000,
        });
        // wx.navigateTo({
        //   url: '/pages/usercenter/address/list/index'
        // });
        break;
      }
      case 'ask': {

        break;
      }
      case 'clean': {
        Toast({
          context: this,
          selector: '#t-toast',
          message: '你点击了清除缓存',
          icon: '',
          duration: 1000,
        });
        break;
      }
      default: {
        break;
      }
    }
  },
  //小程序客服
  handleContact(e) {
    console.log(e.detail.path, 'e.detail.path')
    console.log(e.detail.query)
  },
  //点击唤起拨号盘
  callPhone() {
    wx.makePhoneCall({
      phoneNumber: this.data.phone,
    })
  },
  jumpNav(e) {
    const status = e.detail.tabType;
    console.log('eded', status)

    if (status === 0) {
      wx.navigateTo({
        url: '/pages/order/after-service-list/index'
      });
    } else {
      wx.navigateTo({
        url: `/pages/order/order-list/index?status=${status}`
      });
    }
  },

  jumpAllOrder() {
    wx.navigateTo({
      url: '/pages/order/order-list/index'
    });
  },

  openMakePhone() {
    this.setData({
      showMakePhone: true
    });
  },

  closeMakePhone() {
    this.setData({
      showMakePhone: false
    });
  },

  gotoUserEditPage() {
    const {
      currAuthStep
    } = this.data;
    console.log(currAuthStep, 'currAuthStep')
    if (currAuthStep === 2) {
      wx.navigateTo({
        url: '/pages/usercenter/person-info/index'
      });
    } else {
      this.fetUseriInfoHandle();
    }
  },

  getVersionInfo() {
    const versionInfo = wx.getAccountInfoSync();
    const {
      version,
      envVersion = __wxConfig
    } = versionInfo.miniProgram;
    this.setData({
      versionNo: envVersion === 'release' ? version : envVersion,
    });
  },
});